import {
  Cartesian2,
  Cartesian3,
  Color,
  ConstantPositionProperty,
  createGuid,
  defined,
  Entity,
  HorizontalOrigin,
  Viewer,
} from "cesium";
import { GCS, MathUtils, MouseHandler } from "../CustomCesium/CustomCesium";
import _ from "lodash";

/**
 * description: 获取位置
 * fileName: Position.ts
 * author: ssr
 * date: 2023-01-12 17:30:41
 * version: V1.0.0
 */
export default class MeasurePosition {
  private viewer: Viewer;
  private mouseHandlerManager: MouseHandler;
  private guid: string;
  // 实体
  private entity: Entity | null;
  // 实体id
  private entityId: string;

  constructor(viewer: Viewer, mouseHandlerManager: MouseHandler) {
    this.mouseHandlerManager = mouseHandlerManager;
    this.guid = createGuid();
    this.entityId = "measurePosition_" + this.guid;
    this.entity = null;
    this.viewer = this.init(viewer);
  }

  private init(viewer: Viewer) {
    if (!defined(viewer)) throw new Error("EventListener,无效的视图对象！");
    return viewer;
  }

  /**
   * 测量
   */
  measuring() {
    try {
      if (this.mouseHandlerManager.isExists("measureLeftClick_" + this.guid)) {
        return;
      }
      // 监听鼠标左键
      this.mouseHandlerManager.addLeftMouseClickHandler(
        "measureLeftClick_" + this.guid,
        ({ screenPosition }) => {
          // 贴地坐标or空间坐标
          const position =
            screenPosition &&
            MathUtils.getSurfaceCartesian3(this.viewer, screenPosition);

          // 无有效坐标，不能结束
          if (!position) return;
          if (!defined(position)) return;
        }
      );

      // 鼠标移动事件回调处理
      // 移除上一个实体，添加新实体
      const throttle = _.throttle((screenPosition: Cartesian2) => {
        // 贴地坐标or空间坐标
        const position =
          screenPosition &&
          MathUtils.getSurfaceCartesian3(this.viewer, screenPosition);

        // 无有效坐标，不能结束
        if (!position) return;
        if (!defined(position)) return;

        this.viewer.container.style.cursor = "pointer";

        if (this.entity) {
          this.entity.position = new ConstantPositionProperty(position);
        } else {
          this.entity = this.displayPosition(this.entityId, position);
          this.viewer.entities.add(this.entity);
        }
      }, 350);

      // 监听鼠标移动事件
      this.mouseHandlerManager.addMouseMoveHandler(
        "measureMouseMove_" + this.guid,
        ({ screenPosition }) => {
          // 频繁触发
          // 节流处理
          screenPosition && throttle(screenPosition);
        }
      );

      // 右键结束绘画
      this.mouseHandlerManager.addRightMouseClickHandler(
        "measureRightClick_" + this.guid,
        ({ screenPosition }) => {
          // 删除监听事件
          this.mouseHandlerManager.destroyHandlerByKey(
            "measureLeftClick_" + this.guid
          );
          this.mouseHandlerManager.destroyHandlerByKey(
            "measureMouseMove_" + this.guid
          );
          this.mouseHandlerManager.destroyHandlerByKey(
            "measureRightClick_" + this.guid
          );

          // 贴地坐标or空间坐标
          const position =
            screenPosition &&
            MathUtils.getSurfaceCartesian3(this.viewer, screenPosition);

          // 无有效坐标，不能结束
          if (!position) return;
          if (!defined(position)) return;

          // 删除实体
          this.viewer.entities.removeById(this.entityId);
          this.entity = null;
          
          this.viewer.container.style.cursor = "default";
        }
      );
    } catch (error) {
      console.error("drawManager:", error);
    }
  }

  /**
   * 测量点坐标
   */
  displayPosition(id: string, position: Cartesian3) {
    const gcs: GCS = MathUtils.car3ToGCS(this.viewer, position);
    const text =
      "经度：" +
      gcs.longitude.toFixed(12) +
      "\n纬度：" +
      gcs.latitude.toFixed(12) +
      "\n高度：" +
      gcs.height.toFixed(12);
    const shape = new Entity({
      id,
      name: "drawPoint",
      position: position,
      point: {
        pixelSize: 3,
        outlineColor: Color.BLUE,
        outlineWidth: 3,
      },
      label: {
        text: text,
        fillColor: Color.WHITE,
        showBackground: true,
        backgroundColor: Color.fromCssColorString("rgba(22, 171, 216, 0.5)"),
        font: "14px sans-serif",
        horizontalOrigin: HorizontalOrigin.LEFT,
        pixelOffset: new Cartesian2(10, 0),
      },
    });
    return shape;
  }

  /**
   * 清空
   */
  clearAll() {
    // 删除监听事件
    this.mouseHandlerManager.destroyHandlerByKey(
      "measureLeftClick_" + this.guid
    );
    this.mouseHandlerManager.destroyHandlerByKey(
      "measureMouseMove_" + this.guid
    );
    this.mouseHandlerManager.destroyHandlerByKey(
      "measureRightClick_" + this.guid
    );
    // 删除实体
    this.viewer.entities.removeById(this.entityId);

    this.viewer.container.style.cursor = "default";
  }
}
